package toOffer;

/**
 * <h3>leetcode</h3>
 *
 * @author BigFaceCat
 * @date 2024/1/27 17:00
 * @description <p>两数相加 II</p>
 */
public class toOffer4_4_25 {
    public static void main(String[] args) {

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        return null;
    }

    /**
     * 需要反转链表
     * @param l1
     * @param l2
     * @return
     */
    public static ListNode addTwoNumbers1(ListNode l1, ListNode l2) {
        ListNode node1 = reverseList(l1);
        ListNode node2 = reverseList(l2);

        return reverseList(add(node1, node2));
    }

    //反转链表
    public static ListNode reverseList(ListNode head) {
        //判空
        if (head == null) {
            return null;
        }
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }

        return pre;
    }

    //两链表相加
    public static ListNode add(ListNode l1, ListNode l2) {
        //判空
        if (l1 == null && l2 == null) {
            return null;
        }

        int count = 0;
        ListNode head = null;
        ListNode tail = null;
        while (l1 != null || l2 != null) {

            int value = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + count;
            if (head == null) {
                head = tail = new ListNode(value % 10);
            } else {
                tail.next = new ListNode(value % 10);
                tail = tail.next;
            }

            count = value / 10;

            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;

            if (count >= 1){
                tail.next = new ListNode(count);
            }
        }

        return head;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

//        public int getVal(){
//            return this.val;
//        }

    }
}
